import { getCookie, deleteCookie } from "../js/cookie.js";
import { searchGoodsListLimit,} from "../js/interface.js"

var cookie = document.cookie;
if (cookie) {
    var user = getCookie("lgc");
    if (user) {
        $(".hide a:first-child").css("display", "none");
        $(".hide a:last-child").css("display", "block");
        $(".hide").eq(0).children().html(`欢迎,${user}`)
        $(".exit").click(function () {
            deleteCookie("lgc");
            location.reload();
        })
    }
}

$(".ple").click(function () {
    location.href = "../html/login.html?returnUrl=" + encodeURIComponent(location.href);
})


var key = "";
var orderCol = "goodsPrice";
var orderType = "asc";
var pageIndex = 1;
var showNum = 8;

loadList();

async function loadList(){
    var result = await searchGoodsListLimit({ key, orderCol, orderType, pageIndex, showNum });
    var { status, msg, list, currentIndex, count, maxPage } = result;
    if(status){
        if(list.length){
            var html = "";
            list.forEach(({ goodsId, goodsImg, goodsName, goodsPrice }) => {
                var shopprice = (goodsPrice*1).toFixed(2);
                html +=`<li class="goodsOne">
                <a href="../html/details.html?${goodsId}">
                    <div class="gimg">
                        <img src="http:${goodsImg}" alt="">
                    </div>
                    <p class="gname">${goodsName}</p>
                    <div class="gprice">￥&ensp;${shopprice}</div>
                </a>
            </li>`
            })
            $(".goodsAll").html(html);

            pageIndex = pageIndex > maxPage ? maxPage : pageIndex;
            $(".pageTips").html(`${currentIndex}/${maxPage}`);

            //切换页面
            $(".prev").off();
            $(".prev").click(function () {
                if (pageIndex <= 1) return false;
                pageIndex--;
                
                console.log(pageIndex);
                loadList();
            })

            $(".next").off();
            $(".next").click(function () {
                if (pageIndex >= maxPage) return false;
                pageIndex++;
                console.log(pageIndex);
                loadList();
            })
        }else{
            $(".goodsAll").html(`暂无数据`)
        }
        
    }else{
        alert(msg);
    }
}

$(".sleft a").click(function(){
    key = $(".searchBar").val().trim();
    loadList();
});

$(".asc").click(function(){
    orderType = $(this).val();
    loadList();
});

$(".desc").click(function(){
    orderType = $(this).val();
    // console.log(showNum);
    loadList();
})

$(".select").change(function(){
    showNum = $(this).val();
    loadList();
})